import React, { useEffect, useState } from 'react'

import { useNavigate } from 'react-router'

import styles from './index.module.css'
import { Divider, Input, ConfigProvider, Button, Image, message } from 'antd';
import { CheckShieldOutline, UserOutline, UnlockOutline } from 'antd-mobile-icons'

import { jumpTo } from '../../utils/jump'

import logo from '../../res/logo.png'

//网络
import { getVerificationCode, login } from '../../utils/axiosRequest/api'
//持久化
import { token_cache_key } from '../../utils/cache/cacheKey'
import { putCache } from '../../utils/cache'

//登录页面
function Login() {
    //消息提示
    const [messageApi, contextHolder] = message.useMessage();
    //导航
    const navigate = useNavigate()
    const [userName, setUserName] = useState('')
    const [userPwd, setUserPwd] = useState('')
    const [captcha, seCaptcha] = useState("")

    //验证码
    const [img, setImg] = useState("")
    const [key, setKey] = useState("")
    //点击登录加载状态
    const [isLoadState, seLoadState] = useState(false)
    //登录按钮文字状态
    const [loadBtnStr, seLoadBtnStr] = useState('登录')

    //[]空数组相当于componentDidMount
    useEffect(() => {
        initData()
        return () => {
        }
    }, []);


    function initData() {
        getVerification()
    }

    function clickLogin() {
        if (userName.length === 0) {
            messageApi.open({ type: 'error', content: '请输入账号！' });
            return
        }
        if (userPwd.length === 0) {
            messageApi.open({ type: 'error', content: '请输入密码！' });
            return
        }
        if (captcha.length === 0) {
            messageApi.open({ type: 'error', content: '请输入验证码！' });
            return
        }
        if (captcha.length !== 6) {
            messageApi.open({ type: 'error', content: '请输入6位数验证码！' });
            return
        }
        //开始登录
        seLoadState(true)
        seLoadBtnStr('正在登录...')
        const params = new Map()
        params.set('userName', userName);
        params.set('pwd', userPwd);
        params.set('captcha', captcha);
        params.set('captchaKey', key);
        params.set('channel', 'web');
        login(params)
            .then(response => {
                const data = response.data
                if (data.code === '000') {
                    const repsData = data.data
                    //保存token
                    putCache(token_cache_key, repsData.token)
                    //登录成功
                    jumpTo(navigate, '/main/statistic', true, null)
                } else {
                    //处理失败
                    messageApi.open({ type: 'error', content: data.des });
                }
                seLoadState(false)
                seLoadBtnStr('登录')
            })
            .catch(error => {
                seLoadState(false)
                seLoadBtnStr('登录')
                messageApi.open({ type: 'error', content: error.message });
            });
    }

    function onChangeUserName(val) {
        let userName = val.target.value
        setUserName(userName);
    }

    function onChangeUserPwd(val) {
        let userPwd = val.target.value
        setUserPwd(userPwd);
    }

    function onCaptcha(val) {
        let captcha = val.target.value
        seCaptcha(captcha);
    }

    function clickCaptcha() {
        getVerification()
    }

    function getVerification() {
        const params = new Map()
        getVerificationCode(params)
            .then(response => {
                const data = response.data
                if (data.code === '000') {
                    setImg('data:image/png;base64,' + data.data.imgBase64)
                    setKey(data.data.captchaKey)
                } else {
                    //处理失败
                    messageApi.open({ type: 'error', content: data.des });
                }
            })
            .catch(error => {
                messageApi.open({ type: 'error', content: error.message });
            });
    }


    return (
        <ConfigProvider theme={{
            components: {
                Button: {
                    contentFontSizeSM: 12,//号按钮内容字体大小
                    defaultColor: '#ffffff',//默认字体颜色
                    defaultBg: '#1890ff',//默认背景色
                    defaultHoverColor: '#ffffff',//默认按钮悬浮态文本颜色
                    defaultHoverBg: '#1890ff',//默认按钮悬浮态背景色
                    defaultActiveBg: '#8c8c8c',//	默认按钮激活态背景色
                    defaultActiveColor: '#ffffff',//	默认按钮激活态文字颜色
                    defaultActiveBorderColor: '#8c8c8c',//默认按钮激活态边框颜色
                },
                Input: {
                    activeBorderColor: '#1890ff',
                    hoverBorderColor: '#1890ff',
                },
            }
        }}>
            {contextHolder}
            <div className={styles.container}>
                <div className={styles.login_box}>
                    <div className={styles.title}>
                        <Divider style={{ borderColor: '#1890ff', paddingLeft: '35px', paddingRight: '35px' }}>
                            <Image preview={false} width={45} src={logo} />
                        </Divider>
                    </div>
                    <div className={styles.user_name_box}>
                        <Input onChange={onChangeUserName} value={userName} className={styles.user_name} maxLength='10'
                            placeholder='请输入用户名...' allowClear={true} prefix={<UserOutline />} size="large" />
                    </div>
                    <div className={styles.user_pwd_box}>
                        <Input onChange={onChangeUserPwd} value={userPwd} className={styles.user_pwd} maxLength='20'
                            type={'password'} placeholder='请输入密码...' allowClear={true} prefix={<UnlockOutline />} size="large" />
                    </div>
                    <div className={styles.verification_box}>
                        <div className={styles.verification_con}>
                            <Input onChange={onCaptcha} value={captcha} className={styles.verification} maxLength='6'
                                type={'number'} placeholder='验证码' allowClear={true} prefix={<CheckShieldOutline />} size="large" />
                            <div className={styles.verification_img}>
                                <Image onClick={clickCaptcha} height={"40px"} width={"120px"} src={img} preview={false} placeholder={true}></Image>
                            </div>
                        </div>
                    </div>
                    <div className={styles.login_button_box}>
                        <Button onClick={clickLogin} loading={isLoadState} className={styles.login_button} type="primary" size={'large'}>{loadBtnStr}</Button>
                    </div>
                </div>
            </div>
        </ConfigProvider>
    )
}

export default Login;